package com.tagit.sphinx4;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;

import edu.cmu.sphinx.frontend.BaseDataProcessor;
import edu.cmu.sphinx.frontend.Data;
import edu.cmu.sphinx.frontend.DataProcessingException;
import edu.cmu.sphinx.frontend.DoubleData;
import edu.cmu.sphinx.frontend.endpoint.SpeechClassifiedData;
import edu.cmu.sphinx.frontend.endpoint.SpeechEndSignal;
import edu.cmu.sphinx.frontend.endpoint.SpeechStartSignal;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4String;

/** 
 * Logs the recorded Audio Data and store the received
 *         {@link DoubleData} into a pcm file.
 * @author	Mohamed Ali
 */
public class DataLogger extends BaseDataProcessor {
	private FileOutputStream fos;
	private DataOutputStream dos;

	@S4String(defaultValue = "audio.pcm")
	public static final String PROP_OUTPUT_FILE = "outFile";

	private String outFile;

	public DataLogger() {
	}

	public DataLogger(String outFile) {
		initLogger();
		this.outFile = outFile;		
		initialize();
	}

	@Override
	public void initialize() {
		try {

			fos = new FileOutputStream(outFile);
			dos = new DataOutputStream(fos);
			System.out.println("Created File ");
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.initialize();
	}

	@Override
	public void newProperties(PropertySheet ps) throws PropertyException {
		super.newProperties(ps);
		
		outFile = ps.getString(PROP_OUTPUT_FILE);
		
		logger = ps.getLogger();
		initialize();
	}

	@Override
	public Data getData() throws DataProcessingException {
		Data data = getPredecessor().getData();

		if (logger.isLoggable(Level.INFO)) {
			System.out.println(data);
		}

		if (data instanceof SpeechStartSignal) {
			dos = new DataOutputStream(fos);
		}

		if (data instanceof DoubleData) {
			DoubleData buff = (DoubleData) data;
			double[] values = buff.getValues();
			for (int i = 0; i < values.length; i++) {
				if (logger.isLoggable(Level.FINE)) {
					System.out.print(values[i] + " ");
				}
				try {
					dos.writeShort((short) values[i]);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (logger.isLoggable(Level.FINE)) {
				System.out.println();
			}
		}

		if (data instanceof SpeechClassifiedData) {
			System.out.println(((SpeechClassifiedData) data).isSpeech());
		}

		if (data instanceof SpeechEndSignal) {
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return data;
	}
}
